package com.pks.datacenter.config;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.pks.datacenter.handler.SpringContextHolder;

@SuppressWarnings({"rawtypes","unchecked"})
public class RedisCache implements Cache {
    //当前放入缓存的mapper的namespace
    private final String id;
	private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //默认必须存在的方法,参数是mapper.xml文件中的namespace，也是缓存中作为hash的key
    public RedisCache(String id) {
        this.id = "mybatis_cache:" + id;
    }
    //返回cache唯一表示
    @Override
    public String getId() {
    	return "mybatis_cache:" + this.id;
//        return this.id;
    }
    //获取redisTemplate对象
	private RedisTemplate getRedisTemplate(){ 
        //通过application工具类获取redisTemplate
		RedisTemplate redisTemplate = (RedisTemplate) SpringContextHolder.getBean("redisTemplate");
        //设置key和hash的序列化方式。
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
    // 缓存中放入数据
    @Override
    public void putObject(Object key, Object value) {
        //使用redisHash类型作为缓存存储模型 key hashkey value
    	if (value != null) {
    		getRedisTemplate().opsForHash().put(id,key.toString(),value );
//    		getRedisTemplate().opsForValue().set(key.toString(), value , 1 , TimeUnit.DAYS);
    	}
    }
    //缓存中获取数据
    @Override
    public Object getObject(Object o) {
        //根据key从redis的hash类型中获取数据
        return  getRedisTemplate().opsForHash().get(id.toString(),o.toString());
    }
    //这个方法为mybatis方法，默认没有实现
    @Override
    public Object removeObject(Object o) {
        //根据指定key删除缓存
        return null;
    }
    //增删改走的都是这个方法，删除
    @Override
    public void clear() {
       //清空缓存
        getRedisTemplate().delete(id);
    }
    //用来计算缓存数量
    @Override
    public int getSize() {
        return getRedisTemplate().opsForHash().size(id.toString()).intValue();
    }
	@Override
	public ReadWriteLock getReadWriteLock() {
		return readWriteLock;
	}
}
